<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/2/28
 * Time: 18:05
 */

namespace app\controllers;

use app\models\Permission;
use Yii;
use yii\helpers\Url;
use app\models\User;
use yii\helpers\VarDumper;
use yii\web\NotFoundHttpException;

class UserController extends BaseController
{
    /**
     * 用户管理列表
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            $query = User::find()->where(['<>','id',Yii::$app->params['super_user_id']])->orderBy('id desc');
            $count = $query->count();

            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->asArray()->all();
            foreach ($data as &$d){
                $d['edit_url'] = Url::to(['edit','id'=>$d['id']]);
                $d['reset_password_url'] = Url::to(['reset-password','id'=>$d['id']]);
                $d['destroy_url'] = Url::to(['destroy','id'=>$d['id']]);
                $d['role_url'] = Url::to(['role','id'=>$d['id']]);
                $d['permission_url'] = Url::to(['permission','id'=>$d['id']]);
                $d['roles'] = Yii::$app->authManager->getRolesByUser($d['id']);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        return $this->render('index');
    }

    /**
     * 添加用户
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new User();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'create';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','添加成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('create',['model'=>$model]);
    }

    /**
     * 编辑用户
     * @param int $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionEdit($id)
    {
        $model = User::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('用户不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'edit';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','更新成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('edit',['model'=>$model]);
    }

    /**
     * 删除用户
     * @param $id
     * @return \yii\web\Response
     * @throws \Throwable
     */
    public function actionDestroy($id)
    {
        if (Yii::$app->request->isPost){
            $model = User::findOne($id);
            if ($model===null){
                return $this->asJson(['code'=>1,'msg'=>'用户不存在']);
            }
            $transaction = User::getDb()->beginTransaction();
            try{
                //移除用户的所有权限
                Yii::$app->authManager->revokeAll($model->id);
                //删除用户
                $model->delete();
                $transaction->commit();
                return $this->asJson(['code'=>0,'msg'=>'删除成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'删除失败']);
            }
        }
        return $this->asJson(['code'=>1,'msg'=>'请求错误']);
    }

    /**
     * 重置密码
     * @param $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionResetPassword($id)
    {
        $model = User::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('用户不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'reset-password';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','重置密码成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('reset-password',['model'=>$model]);
    }

    /**
     * 分配权限
     * @param $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionRole($id)
    {
        $model = User::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('用户不存在');
        }
        $auth = Yii::$app->authManager;
        //所有角色
        $roles = $auth->getRoles();
        //用户已拥有角色
        $ownRoles = $auth->getRolesByUser($id);

        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $transaction = User::getDb()->beginTransaction();
            try{
                //删除原来有的角色
                foreach ($ownRoles as $k=>$role){
                    $auth->revoke($role,$id);
                }
                //添加新的角色
                if (isset($data['role'])&&is_array($data['role'])){
                    foreach ($data['role'] as $role_string){
                        $role = $auth->getRole($role_string);
                        $auth->assign($role,$id);
                    }
                }
                $transaction->commit();
                Yii::$app->session->setFlash('info','分配角色成功');
                return $this->redirect(['index']);
            }catch (\Exception $exception){
                $transaction->rollBack();
            }

            if ($model->load($data,'assign')&&$model->assignRole()){
                Yii::$app->session->setFlash('info','分配角色成功');
                return $this->redirect(['index']);
            }
        }

        return $this->render('role',['model'=>$model,'roles'=>$roles,'ownRoles'=>$ownRoles]);
    }

    public function actionPermission($id)
    {
        $model = User::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('用户不存在');
        }
        $auth = Yii::$app->authManager;
        //所有权限
        $permission = Permission::tree();
        //用户已拥有权限
        $ownPermission = $auth->getPermissionsByUser($id);

        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post('permission',[]);
            //移除所拥有的权限
            foreach ($ownPermission as $o){
                $auth->revoke($o,$id);
            }
            //添加新的权限
            foreach ($data as $d){
                $permission = $auth->getPermission($d);
                $auth->assign($permission,$id);
            }
            Yii::$app->session->setFlash('info','分配权限成功');
            return $this->redirect(['index']);
        }

        return $this->render('permission',['model'=>$model,'permission'=>$permission,'ownPermission'=>$ownPermission]);
    }

}